
package com.probiz.estore.framework.test;

import org.springframework.test.AbstractTransactionalDataSourceSpringContextTests;

import com.probiz.estore.core.util.GenericsUtils;
import com.probiz.estore.core.util.Log4jUtil;
import com.probiz.estore.core.util.StringUtil;

/**
 * 重构为基于范型
 * @param <T>
 */
public abstract class BaseGenericTransactionalTestCase<T> extends
		AbstractTransactionalDataSourceSpringContextTests {

	static long	startTime;

	// This static block ensures that Spring's BeanFactory is only loaded
	// once for all tests
	static {
		System.out.println("Starting test case...");
		startTime = System.currentTimeMillis();
		Log4jUtil.initLogging(null);
	}

	protected final static StringBuilder formatMsg(String msgWithFormat,
			Object... args) {
		return StringUtil.format(msgWithFormat, args);
	}

	protected Class<T>	entityClass;		// DAO所管理的Entity类型.

	protected String	entityClassName;

	protected String	entityIdName;

	/**
	 * 这里进行数据的初始化，根据约定的规则。如果要用自定义的规则，可以通过子类构造函数、init方法、setter方法等进行修改。
	 */
	public BaseGenericTransactionalTestCase() {
		entityClass = GenericsUtils.getSuperClassGenricType(getClass());
		entityClassName = entityClass.getSimpleName().substring(0, 1)
				.toLowerCase()
				+ entityClass.getSimpleName().substring(1);
		entityIdName = entityClassName + "Id";
	}

	@Override
	protected String[] getConfigLocations() {
		setAutowireMode(AUTOWIRE_BY_NAME);
		return new String[] { "classpath*:conf/spring-context-test.xml" };
	}

	protected T getSampleEntity() {
		fail("Not yet implemented");
		return null;
	}

	protected final void logDebug(String msg, Object... args) {
		if (logger.isDebugEnabled()) {
			logger.debug(StringUtil.format(msg, args));
		}
	}

	protected final void logError(String msg, Object... args) {
		logger.error(StringUtil.format(msg, args));
	}

	protected final void logInfo(String msg, Object... args) {
		if (logger.isInfoEnabled()) {
			logger.info(StringUtil.format(msg, args));
		}
	}

	protected final void logWarn(String msg, Object... args) {
		if (logger.isWarnEnabled()) {
			logger.warn(StringUtil.format(msg, args));
		}
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see org.springframework.test.AbstractTransactionalSpringContextTests#onTearDownAfterTransaction()
	 */
	@Override
	protected void onTearDownAfterTransaction() throws Exception {
		super.onTearDownAfterTransaction();
		logInfo("Test case completed, time spent: [%1 secs %2 ms].", ((System
				.currentTimeMillis() - startTime) / 1000), ((System
				.currentTimeMillis() - startTime) % 1000));
		startTime = System.currentTimeMillis();
	}
}
